package src.Fifteen;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;

public class ThreadNameTest extends JFrame {

    JTable table;

    JTextField textField1;

    JTextField textField2;

    protected void do_this_windowActivated(WindowEvent e){
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        Thread[] threads = new Thread[group.activeCount()];
        group.enumerate(threads);
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);
        model.setColumnIdentifiers(new Object[]{"线程ID","线程名称"});
        for (Thread thread : threads){
            model.addRow(new Object[]{thread.getId(),thread.getName()});
        }
        table.setModel(model);
    }

    protected void do_button1_actionPerformed(ActionEvent e){
        Object[] newThread = null;
        String name = textField1.getText();
        if(name.isEmpty()){
            Thread thread = new Thread(new Forever(),name);
            thread.start();
            newThread = new Object[]{thread.getId(),thread.getName()};
        }else {
            Thread thread = new Thread(new Forever(),name);
            thread.start();
            newThread = new Object[]{thread.getId(),name};
        }

        ((DefaultTableModel)table.getModel()).addRow(newThread);
    }

    protected void do_button2_actionPerformed(ActionEvent e){
        int selectedRow = table.getSelectedRow();
        String newName = textField2.getText();
        if((selectedRow == -1) || newName.isEmpty()){
            return;
        }
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setValueAt(newName,selectedRow,1);
        repaint();
    }

}
